﻿using Conversive.PHPSerializationLibrary;
using SKIT.FlurlHttpClient.Wechat.Api;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Flurl.Http;
using Furion;
using Furion.Logging;
using Furion.Schedule;
using Serilog;
using SKIT.FlurlHttpClient.Wechat.Api.Models;
using Newtonsoft.Json;

namespace MqttClient.Jobs
{
    [PeriodSeconds(150)]
    [JobDetail(jobId: "微信销假通知", description: "微信销假通知", GroupName = "系统", Concurrent = false)]
    public class XiaojiaNoticeJob : IJob
    {

        public string server = "https://weixin.tslexunbao.com";

        //        ConnectionMultiplexer redis;
        string pkey = "easywechat.kernel.access_token*";
        static string key = "";
        PhpSerializer ps = new PhpSerializer();
        static bool send = false;

        /// <summary>
        ///  微信token
        /// </summary>
        private string token;

        private readonly WechatApiClientOptions options;
        ILogger loger;

        public XiaojiaNoticeJob(ILogger loger)
        {
            this.loger = loger;
            options = new WechatApiClientOptions()
            {
                AppId = "wx42a8bcc9d53bcf3b",
                AppSecret = "673321d209f6c3e3b4d8d9eb6fce56a6",
            };

        }




        /// <summary>
        /// 微信通知
        /// </summary>
        /// <param name="context"></param>
        /// <param name="stoppingToken"></param>
        /// <returns></returns>
        public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
        {
            loger.Warning("Xiao jia chcek " + DateTime.Now.ToString());
              Console.WriteLine("Xiao jia chcek");
            {
                // var services = scope.ServiceProvider;
                try
                {
                    var server = RedisHelper.GetServer("127.0.0.1", 6379);
                    while (String.IsNullOrEmpty(key))
                    {


                        await "https://weixin.tslexunbao.com/wxapi/app/acctoken".GetAsync();


                        foreach (var akey in RedisHelper.GetLikeKeys(pkey))
                        {
                            //  Console.WriteLine(key);
                            key = akey;
                            Console.WriteLine(akey);
                        }

                        Thread.Sleep(1000);

                    }

                    var dbredis = RedisHelper.GetDatabase();
                    var str = (dbredis.StringGet(key));
                    if (!String.IsNullOrEmpty(str))
                    {


                        var t = (Dictionary<object, object>)ps.Deserialize(str);
                        if (t.ContainsKey("access_token"))
                        {
                            token = t["access_token"].ToString();

                        }




                        Console.ForegroundColor = ConsoleColor.White;

                        var wxtz = App.GetService<WeixinTongzhi>(); // services.GetService<WeixinTongzhi>();
                        using (var unsend = wxtz.getXJUnsend())
                        {
                            // 获取小时数

                            foreach (DataRow kaoqin in unsend.Rows)
                            {
                                try
                                {


                                    using (var untz = wxtz.getBindTeacher(kaoqin["teacher"].ToString()))
                                    {

                                        foreach (DataRow guanzhu in untz.Rows)
                                        {

                                            Console.WriteLine(guanzhu["oauth_id"]);
                                            string faqi = wxtz.getQingjiaUser(kaoqin["id"].ToString());
                                            LevelMsg(token, kaoqin, faqi,guanzhu);



                                        }


                                    }


                                }
                                catch (Exception e)
                                {
                                   loger.Error($"{e.Message} ");

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine(e.Message);
                                    Console.ForegroundColor = ConsoleColor.White;
                                }
                                wxtz.xjSended(Convert.ToInt32(kaoqin["id"]));


                            }

                        }

                        wxtz.close();

                    }


                }
                catch (Exception e)
                {
                    StringLoggingPart.Default().SetMessage($"{e.Message} ").LogError();
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("微信通知 失败 " + e.Message + e.StackTrace);
                    if (e.InnerException != null)
                    {

                        Console.WriteLine("微信通知 失败 " + e.InnerException.Message + e.InnerException.StackTrace);
                    }

                    Console.ForegroundColor = ConsoleColor.White;
                }

              

            }

        }

        /// <summary>
        /// 发送消假通知
        /// </summary>
        /// <param name="token"></param>
        private void LevelMsg(string token, DataRow stu,string faqi, DataRow laos)
        {



            CgibinMessageTemplateSendRequest tplr = new CgibinMessageTemplateSendRequest();
            tplr.TemplateId = TplIds.请假取消通知;
            tplr.Data = new Dictionary<string, CgibinMessageTemplateSendRequest.Types.DataItem>();
            // 头
         
            // 姓名
            tplr.Data.Add("thing1",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                    { Value = stu["username"].ToString(), Color = "#173177" });
            // 班级
            tplr.Data.Add("thing2",
                new CgibinMessageTemplateSendRequest.Types.DataItem
                    { Value = stu["clname"].ToString() });
            // 请假发起人
            tplr.Data.Add("thing3",
                new CgibinMessageTemplateSendRequest.Types.DataItem { Value = faqi });

            var time7 = Convert.ToDateTime(stu["timee"]).ToString("yyyy-MM-dd HH:mm");
            var time5 = Convert.ToDateTime(stu["ctime"]).ToString("yyyy-MM-dd HH:mm");
          
            tplr.Data.Add("time7",
                new CgibinMessageTemplateSendRequest.Types.DataItem { Value = time7 });
            tplr.Data.Add("time5",
                new CgibinMessageTemplateSendRequest.Types.DataItem { Value = time5 });
            tplr.Url = "http://weixin.tslexunbao.com/teacher/qingjia/detail/" + stu["id"];

#if DEBUG
            tplr.ToUserOpenId = "oyXHL0qFna08ZW-mnlDUiYEjOMW8";
#else
            tplr.ToUserOpenId = laos["oauth_id"].ToString();
#endif

            tplr.AccessToken = token;
            //tplr.Url = "";


            var client = new WechatApiClient(options);
            client.ExecuteCgibinMessageTemplateSendAsync(tplr).ContinueWith((res =>
            {
                Console.WriteLine($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm")} {stu["clname"]} 销假提醒 {stu["username"]} {tplr.ToUserOpenId}->{stu["id"]}  {res.Result.ErrorMessage}");

                loger.Information($"{DateTime.Now.ToString("yyyy/MM/dd HH:mm")} {stu["clname"]} 销假提醒 {stu["username"]}  {JsonConvert.SerializeObject(tplr)}{tplr.ToUserOpenId}->{stu["id"]}  {res.Result.ErrorMessage}");
            }));


        }
    }
}
